<template>
  <div class="dashboard">
    <el-row :gutter="20" type="flex" justify="start" align="middle" style="gap: 10px;">
      <el-col :span="7">
        <date-range-picker
            :start-date="startDate"
            :end-date="endDate"
            @update:startDate="startDate = $event"
            @update:endDate="endDate = $event"
            style="width: 350px;"
        />
      </el-col>
      <el-col :span="9">
        <el-button  style="margin-left: 15px;" type="primary"  @click="filterData">筛选</el-button>
        <el-button id="reset-button" type="default"  @click="resetFilter" >重置</el-button>
      </el-col>
    </el-row>
    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="8">
        <pressure-chart :chart-data="pressureChartData" :x-axis="timeAxis" />
      </el-col>
      <el-col :span="8">
        <main-force-chart :chart-data="mainForceChartData" :x-axis="timeAxis" />
      </el-col>
      <el-col :span="8">
        <speed-chart :chart-data="speedChartData" :x-axis="timeAxis" />
      </el-col>
    </el-row>
    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="24">
        <el-radio-group v-model="selectedSensor" @change="handleSensorChange">
          <el-radio  :value="sensor" v-for="sensor in sensors" :key="sensor">{{ sensor }}</el-radio>
        </el-radio-group>
      </el-col>
    </el-row>
    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="24">
        <data-table
            :filtered-data="filteredData"
            :current-page="currentPage"
            :page-size="pageSize"
            :total="total"
            :total-pages="totalPages"
            @current-change="handleCurrentChange"
        />
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { getRecentChartData, getRecentTableData,
  getFilteredChartData, getFilteredTableData} from '@/api/dataService';
import PressureChart from '@/components/Chart/PressureChart.vue';
import MainForceChart from '@/components/Chart/MainForceChart.vue';
import SpeedChart from '@/components/Chart/SpeedChart.vue';
import DataTable from '@/components/Table/DataTable.vue';
import DateRangePicker from '@/components/DateRangePicker/DateRangePicker.vue';

export default {
  name: 'DashboardView',
  components: {
    PressureChart,
    MainForceChart,
    SpeedChart,
    DataTable,
    DateRangePicker
  },
  data() {
    return {
      startDate: '',
      endDate: '',
      selectedSensor: '压头行程', // 默认选中
      sensors: ['压头行程', '主缸压力', '速度'],
      currentPage: 1,
      pageSize: 6,
      total: 0,
      totalPages: 1,
      // tableData: [],
      allTableData: [], // 所有表格数据
      filteredTableData: [], // 筛选后的数据
      pressureChartData: [],
      mainForceChartData: [],
      speedChartData: [],
      timeAxis: this.generateTimeAxis(),
      isFiltering: false  // 用于标记当前是否处于筛选状态
    };
  },

  computed: {
    filteredData() {
      // 返回当前页的数据
      // console.log('filteredTableData:', this.filteredTableData.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize));
      // return this.filteredTableData.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize);
      return this.filteredTableData;
    }
  },
  // watch: {
  //   // 监听 allTableData 的变化，并在变化时更新 filteredTableData
  //   allTableData(newVal) {
  //     this.updateFilteredData(newVal);
  //   }
  // },
  methods: {

    generateTimeAxis() {
      const now = new Date();
      const times = [];
      // const interval = 1; // 每分钟一个标注，总共31个点

      for (let i = 60; i >= 0; i--) {
        const time = new Date(now.getTime() - i * 30 * 1000);//30s一个点

        // 确保小时和分钟都是两位数
        const hours = String(time.getHours()).padStart(2, '0');
        const minutes = String(time.getMinutes()).padStart(2, '0');
        const seconds = String(time.getSeconds()).padStart(2, '0');

        times.push(`${hours}:${minutes}:${seconds}`);
      }

      return times;
    },
    generateTimeAxisForFilteredData() {
      const startTime = new Date(this.startDate);
      const endTime = new Date(this.endDate);
      const timeInterval = (endTime - startTime) / 60; // 均分成7个点
      const times = [];
      for (let i = 0; i <= 60; i++) {
        const time = new Date(startTime.getTime() + i * timeInterval);

        const year = time.getFullYear();
        const month = String(time.getMonth() + 1).padStart(2, '0');
        const day = String(time.getDate()).padStart(2, '0');
        const hours = String(time.getHours()).padStart(2, '0');
        const minutes = String(time.getMinutes()).padStart(2, '0');
        const seconds = String(time.getSeconds()).padStart(2, '0');

        times.push(`${year}-${month}-${day} ${hours}:${minutes}:${seconds}`);
      }
      // this.timeAxis = times.map(time => time.split(' ')[1]); // 仅展示时间部分
      this.timeAxis = times;
      // console.log('this.timeAxis:', this.timeAxis);
    },



    async fetchTableData(page = 1) {
      try {

        const tableResponse = await getRecentTableData(page, this.pageSize, this.getSensCode(this.selectedSensor));
        const tableData = tableResponse.data.records;
        this.allTableData = tableData;
        this.total = tableResponse.data.total;
        this.totalPages = tableResponse.data.pages;
        if(tableResponse.data.pages === 0){this.totalPages = 1;}
        this.currentPage = tableResponse.data.current;

        this.processTableData(tableData);
      } catch (error) {
        console.error('Error fetching data:', error);
      }
    },
    async fetchChartData() {
      try {
        const sensorCodes = ['5TES1701MM1', '5TES1702MP', '5TES1702MM2'];

        const chartPromises = sensorCodes.map(code => getRecentChartData(code));
        const chartResponses = await Promise.all(chartPromises);

        const pressureData = this.processChartData(chartResponses[0].data);
        const mainForceData = this.processChartData(chartResponses[1].data);
        const speedData = this.processChartData(chartResponses[2].data);

        this.pressureChartData = this.fillMissingDataPoints(pressureData);
        this.mainForceChartData = this.fillMissingDataPoints(mainForceData);
        this.speedChartData = this.fillMissingDataPoints(speedData);
      } catch (error) {
        console.error('Error fetching chart data:', error);
      }
    },

    processChartData(data) {
      return data.map(item => {
        const time = item.createTime.split(' ')[1]; // 获取时间部分
        return {
          time: time, // 保留到秒级别
          value: item.measureValue,
        };
      });
    },
    processFilteredChartData(data) {
      return data.map(item => {
        const date = item.createTime.split(' ')[0]; // 获取日期部分
        const time = item.createTime.split(' ')[1]; // 获取时间部分
        return {
          time: `${date} ${time}`, // 包含日期和时间
          value: item.measureValue,
        };
      });
    },

    processTableData(data) {
      const processedData = data.map(item => {
        return {
          seq: item.serialNumber,
          // time: item.createTime.split(' ')[1].substring(0, 5),
          time: item.createTime.split(' ')[1],
          sensor: item.sensorName,
          value: item.measureValue,
          sensCode: item.sensCode
        };
      });

      this.allTableData = processedData;

      // this.filteredTableData = filtered; // 更新筛选后的数据
      this.filteredTableData = processedData; // 更新筛选后的数据
    },

    fillMissingDataPoints(data) {
      const timeAxis = this.generateTimeAxis();
      const dataMap = new Map(data.map(item => [item.time, item.value]));

      return timeAxis.map(time => {
        let value = dataMap.get(time);
        if (value === undefined && data.length > 0) {
          // 获取与当前时间点最近的时间点
          const closestData = data.reduce((prev, curr) => {
            const prevTimeDiff = Math.abs(this.timeToSeconds(prev.time) - this.timeToSeconds(time));
            const currTimeDiff = Math.abs(this.timeToSeconds(curr.time) - this.timeToSeconds(time));
            return (currTimeDiff < prevTimeDiff) ? curr : prev;
          }, data[0]);  // 提供初始值

          value = closestData ? closestData.value : undefined;
        }

        return { time, value };
      });
    },
    fillMissingFilteredDataPoints(data) {
      const timeAxis = this.timeAxis;
      // 创建一个包含完整时间（日期和时间）的映射
      const dataMap = new Map(data.map(item => [item.time, item.value]));

      return timeAxis.map(time => {
        let value = dataMap.get(time);

        // 如果没有找到直接对应的值，则寻找最接近的时间点数据
        if (value === undefined && data.length > 0) {
          const closestData = data.reduce((prev, curr) => {
            const prevTimeDiff = Math.abs(new Date(prev.time) - new Date(time));
            const currTimeDiff = Math.abs(new Date(curr.time) - new Date(time));
            return (currTimeDiff < prevTimeDiff) ? curr : prev;
          }, data[0]);

          value = closestData ? closestData.value : null;
        }

        return { time, value: value };
      });
    },


    timeToSeconds(timeStr) {
      const [hours, minutes, seconds] = timeStr.split(':').map(Number);
      return hours * 3600 + minutes * 60 + seconds;
    },
    handleDateChange() {
      console.log('Selected date range:', this.startDate, this.endDate);
    },
    async filterData() {
      if (!this.validateDateRange()) {
        return; // 日期无效
      }
      // console.log('Filtering data from', this.startDate, 'to', this.endDate);
      this.isFiltering = true;
      this.generateTimeAxisForFilteredData();
      await this.fetchFilteredChartData();  // 获取筛选后的图表数据
      await this.fetchFilteredTableData();  // 获取筛选后的表格数据
    },
    async fetchFilteredChartData() {
      try {
        const sensorCodes = ['5TES1701MM1', '5TES1702MP', '5TES1702MM2'];
        const chartPromises = sensorCodes.map(code =>
            getFilteredChartData(this.startDate, this.endDate, code)
        );
        const chartResponses = await Promise.all(chartPromises);

        const pressureData = this.processFilteredChartData(chartResponses[0].data);
        const mainForceData = this.processFilteredChartData(chartResponses[1].data);
        const speedData = this.processFilteredChartData(chartResponses[2].data);

        // console.log('pressureData pressureData pressureData:',pressureData);
        this.pressureChartData = this.fillMissingFilteredDataPoints(pressureData);
        this.mainForceChartData = this.fillMissingFilteredDataPoints(mainForceData);
        this.speedChartData = this.fillMissingFilteredDataPoints(speedData);

        // this.generateTimeAxisForFilteredData();
      } catch (error) {
        console.error('Error fetching filtered chart data:', error);
      }
    },
    async fetchFilteredTableData(page = 1) {
      try {
        const response = await getFilteredTableData(
            this.startDate,
            this.endDate,
            page,
            this.pageSize,
            this.getSensCode(this.selectedSensor)
        );
        const tableData = response.data.records;
        this.processTableData(tableData);
        this.total = response.data.total;
        this.totalPages = response.data.pages;
        this.currentPage = page;
      } catch (error) {
        console.error('Error fetching filtered table data:', error);
      }
    },

    resetFilter() {
      this.startDate = '';
      this.endDate = '';
      // this.startDate = null;
      // this.endDate = null;
      // this.updateTableData();
      this.isFiltering = false;  // 重置为非筛选状态
      this.fetchTableData(this.currentPage);  // 重新获取当前页面的数据
      // 重新生成最近30分钟的时间轴
      this.timeAxis = this.generateTimeAxis();
      this.fetchChartData();
      console.log('Reset filter');
    },
    handleSensorChange(value) {
      // console.log('Selected sensor:', value);
      this.selectedSensor = value;
      this.currentPage = 1;
      if (this.isFiltering) {
        this.fetchFilteredTableData(this.currentPage);
      } else {
        this.fetchTableData(this.currentPage);
      }
      // this.updateTableData();
    },
    handleCurrentChange(page) {
      if (page > 0 && page <= this.totalPages) {
        this.currentPage = page;
        if (this.isFiltering) {
          this.fetchFilteredTableData(this.currentPage);
        } else {
          this.fetchTableData(this.currentPage);
        }
        console.log('currentPage diaoyong:', page);
      }
    },
    getSensCode(sensor) {
      if (sensor === '压头行程') {
        return '5TES1701MM1';
      } else if (sensor === '主缸压力') {
        return '5TES1702MP';
      } else if (sensor === '速度') {
        return '5TES1702MM2';
      }
    },
    // 日期输入验证
    validateDateRange() {
      if (!this.startDate || !this.endDate) {
        return false;
      }
      if (!(new Date(this.startDate) <= new Date(this.endDate))) {
        return false;
      }
      return true;
    },




  },

  mounted() {
    this.fetchTableData().then(() => {
      this.$nextTick(() => {
        this.timeAxis = this.generateTimeAxis();
      });
    });
    this.fetchChartData().then(() => {
      this.$nextTick(() => {
        this.timeAxis = this.generateTimeAxis();
      });
    });
    this.interval = setInterval(() => {
      if (!this.isFiltering) {
        this.fetchTableData();
        this.fetchChartData().then(() => {
          this.$nextTick(() => {
            this.timeAxis = this.generateTimeAxis();
          });
        });
      }
    }, 30000); // 每半分钟更新一次
  },

  beforeUnmount() {
    clearInterval(this.interval);
  }
};
</script>

<style scoped lang="scss">
.dashboard {
  padding: 10px 20px;
  background-color: #000C34;
  color: #C0C4CC; /* 字体颜色 */
}

/* 筛选-重置按钮 */
.el-button {
  @include button-style;
}

#reset-button {
  @include reset-style
}

/* 修改“开始时间”“结束时间”的占位符颜色 */
:deep(.el-date-editor .el-range-input ) {
  color: white;
}


:deep(.el-date-editor .el-range-separator ) {
  color: rgb(189, 189, 189);
}

</style>
